/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2023. All rights reserved.
 */

package validator

import (
	"errors"
	"fmt"
	"prim-server/logger"
	"regexp"

	"github.com/go-playground/locales/en"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	et "github.com/go-playground/validator/v10/translations/en"
)

var (
	uni      *ut.UniversalTranslator
	trans    ut.Translator
	validate *validator.Validate
)

func Init() error {
	uni = ut.New(en.New())
	trans, _ = uni.GetTranslator("en")
	validate = validator.New()

	if err := validate.RegisterValidation("uuid", uuidWithout); err != nil {
		return errors.New("register validation[uuid] err")
	}

	if err := et.RegisterDefaultTranslations(validate, trans); err != nil {
		return errors.New("register validator default translation err")
	}
	return nil
}

func Validate(s interface{}) error {
	if validate == nil {
		err := errors.New("validator is uninitialized")
		logger.Error(err.Error())
		return err
	}
	err := validate.Struct(s)
	if err != nil {
		if _, ok := err.(*validator.InvalidValidationError); ok {
			err = fmt.Errorf("validator un work, error: %v", err)
			logger.Error(err.Error())
			return err
		}
		for _, e := range err.(validator.ValidationErrors) {
			err = fmt.Errorf("parameters invalid: %s", e.Translate(trans))
			logger.Error(err.Error())
			return err
		}
	}
	return nil
}

func uuidWithout(f validator.FieldLevel) bool {
	value := f.Field().String()
	return isUUid(value)
}

func isUUid(str string) bool {
	flag, err := regexp.MatchString(`^[0-9a-f]{32}$`, str)
	if err != nil {
		return false
	}
	return flag
}
